package controller;
//import java.lang.*;
//import java.awt.*;
//import java.awt.event.*;
import javax.swing.*;
//import javax.swing.event.*;
//import java.text.NumberFormat;
import javax.swing.text.*;

/**
 * Class to check for ints and doubles in the JTextField
 * 
 * @author Arjan Frans, Alwin Rombout, Jelte Verbree, Brendan Kanters
 * @version 1.0
 */
public class JTextFieldNumbersOnly extends JTextField
{
    public JTextFieldNumbersOnly(int cols) {
        super(cols);
    }
    public JTextFieldNumbersOnly(String string) {
        super(string);
    }
    
    /**
     * Method to return document
     * @return NumbersOnlyDocument
     */
    protected Document createDefaultModel() {
        return new NumbersOnlyDocument();
    }
    
    /**
     * Method to check if a String is an int
     * @param str
     * @return boolean
     */
    static private boolean isItAnInt(String str){
        try {
            Integer.parseInt(str);
            return true;
        }
        catch(NumberFormatException e) {
            return false;
        }
    }
    /**
     * Method to check if a String is a double
     * @param str
     * @return boolean
     */
    static private boolean isItADouble(String str){
        try {
            Double.parseDouble(str);
            return true;
        }
        catch(NumberFormatException e) {
            return false;
        }
    }
    
    /**
     * Method to check if a String is a dot (.)
     * @param str
     * @return boolean
     */
    static private boolean isItADot(String str){
        if(str.equals(".")){return true;}
        else{return false;}
    }
    
    /**
     * If the String is an int, a double or a dot JTextField will continue
     */
    static class NumbersOnlyDocument extends PlainDocument {
        public void insertString(int offs, String str, AttributeSet a)
        throws BadLocationException {
            
            if(str == null) {
                return;
            }
            if(isItAnInt(str) || isItADouble(str) ||(isItADot(str) && isItAnInt(this.getText(0,(this.getLength()))))){
                super.insertString(offs, str, a);
            }
        }
    }
}